package com.yuyou.fn.updater.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.database.event.EventHandler;
import com.yuyou.fn.common.database.event.IEventHandler;
import com.yuyou.fn.common.service.ISiteConfigService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.platform.entity.BusTeam;
import com.yuyou.fn.platform.service.IBusTeamService;
import com.yuyou.fn.settlement.constant.IncomeCategoryEnum;
import com.yuyou.fn.settlement.constant.Subjects;
import com.yuyou.fn.settlement.entity.ChangeRecord;
import com.yuyou.fn.settlement.vo.FeeCategoryTreeMapVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

@EventHandler(tables = "yyfn.change_record")
@Component
public class StatChangeUpdater implements IEventHandler {

    private final Logger log = LoggerFactory.getLogger(StatChangeUpdater.class);


    @Resource
    private ISiteConfigService siteConfigService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IBusTeamService busTeamService;


    private Map<Long, FeeCategoryTreeMapVo> feeCategoryId2FeeCategoryOfProduct = new HashMap<>();
    private Map<Long, FeeCategoryTreeMapVo> feeCategoryId2FeeCategoryOfGradeSubject = new HashMap<>();

    @PostConstruct
    public void init() {
        foreachFeeCategory(JSONArray.parseArray(siteConfigService.getConfigValueFromCache("product_feeCategory"), FeeCategoryTreeMapVo.class), feeCategoryId2FeeCategoryOfProduct);
        foreachFeeCategory(JSONArray.parseArray(siteConfigService.getConfigValueFromCache("grade_subject_feeCategory"), FeeCategoryTreeMapVo.class), feeCategoryId2FeeCategoryOfGradeSubject);
    }

    private void foreachFeeCategory(List<FeeCategoryTreeMapVo> list, Map<Long, FeeCategoryTreeMapVo> feeCategoryId2FeeCategory) {
        for (FeeCategoryTreeMapVo vo : list) {
            feeCategoryId2FeeCategory.put(vo.getFeeCategoryId(), vo);
            if (vo.getChildren() != null) {
                foreachFeeCategory(vo.getChildren(), feeCategoryId2FeeCategory);
            }
        }
    }


    @Override
    public void insert(String tableName, JSONArray rowList) {
        try {
            build(rowList);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(String tableName, JSONArray rowList, Set<String> updateColumns) {
        try {
            build(rowList);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(String tableName, JSONArray rowList) {

    }

    private void build(JSONArray rowList) throws ParseException {

        List<BusTeam> busTeamList=busTeamService.findListByExample( BusTeam.createExample());
        List<Long> busTeamIds= BeanUtils.toList(busTeamList,"busTeamId");
        for (int i = 0; i < rowList.size(); i++) {
            JSONObject row = rowList.getJSONObject(i);
            ChangeRecord changeRecord = row.toJavaObject(ChangeRecord.class);
            String key=Utils.formatDate(changeRecord.getEffectTime(),"yyyy-MM-dd")+"_"+changeRecord.getMainAccountId();


            if (changeRecord.getDirection() == 0 && Subjects.REAL_INCOME.equals(changeRecord.getSubject()) && busTeamIds.contains(changeRecord.getMainAccountId()) ) {
                /*记录某天某种类型的其中一条流水，后面根据这条流水去更新该天某些类型的成本*/
                Long changeRecordId=redisTemplate.opsForHash().get("oneDayIncomeChange",key)==null?null:Long.parseLong(redisTemplate.opsForHash().get("oneDayIncomeChange",key).toString());
                if (changeRecordId==null  ){
                    redisTemplate.opsForHash().put("oneDayIncomeChange",key,changeRecord.getChangeRecordId().toString());
                }
            }

            if (changeRecord.getDirection() == 0 && (Subjects.REAL_INCOME.equals(changeRecord.getSubject()) && IncomeCategoryEnum.COURSE_INCOME.id == changeRecord.getCategoryId())){
                String changeRecordIds=redisTemplate.opsForHash().get("oneDayClassIncome",key)==null?null:redisTemplate.opsForHash().get("oneDayClassIncome",key).toString();
                List<Long> changeRecordIdList=null;
                if (StringUtils.isNotEmpty(changeRecordIds)){
                    changeRecordIdList=Utils.toLongIds(changeRecordIds);
                }else {
                    changeRecordIdList=new ArrayList<>();
                }
                changeRecordIdList.add(changeRecord.getChangeRecordId());
                redisTemplate.opsForHash().put("oneDayClassIncome",key,StringUtils.join(changeRecordIdList,","));
            }

            if (changeRecord.getDirection() == 0 && ((Subjects.REAL_INCOME.equals(changeRecord.getSubject()) && IncomeCategoryEnum.COURSE_INCOME.id == changeRecord.getCategoryId()) || (Subjects.COST.equals(changeRecord.getSubject()) && feeCategoryId2FeeCategoryOfProduct.containsKey(changeRecord.getCategoryId())) ) ) {
                /*记录某天某种类型的其中一条流水，后面根据这条流水去更新该天的产品线年级科目成本*/
                Long changeRecordId=redisTemplate.opsForHash().get("oneDayRecordChange",key)==null?null:Long.parseLong(redisTemplate.opsForHash().get("oneDayRecordChange",key).toString());
                if (changeRecordId==null  ){
                    redisTemplate.opsForHash().put("oneDayRecordChange",key,changeRecord.getChangeRecordId().toString());
                }
            }

        }

    }

}
